<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class CompanyService
{
    public function insert($input){
        
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        
        $admin = User::where('mobile',$res['mobile'])->first();
        if($admin){
            throw new InvalidRequestException('该手机号已被注册');
        }

        $res['status'] = $res['status'] ? 1 : 0;
        DB::beginTransaction();
        $data = Company::create($res);
        
        $password = '123456';
        $admin = new User();
        $admin->name = $res['contacts'];
        $admin->mobile = $res['mobile'];
        $admin->role_id = 0;
        $admin->status = 1;
        $admin->password = Hash::make($password);
        $admin->save();
        DB::commit();
        return true;
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $res['status'] = $res['status'] ? 1 : 0;
            $data = Company::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function status($data){
        try {
            $data->status =  $data->status ? 0 : 1;
            $data->save();
            if($data->id){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    
}